<?php

use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;

/**
 * SecurityPlugin
 * This is the security plugin which controls that users only have access to the modules they're assigned to
 */
class SecurityPlugin extends Plugin {

    /**
     * This action is executed before execute any action in the application
     *
     * @param Event $event
     * @param Dispatcher $dispatcher
     */
    public function beforeDispatch(Event $event, Dispatcher $dispatcher) {
        $allow = [
            'auth', 'test', 'errors', 'payment'
        ];
        if (!in_array($dispatcher->getControllerName(), $allow)) {
            $accessToken = $this->request->get('token');
            if (empty($accessToken)) {
                $accessToken = $this->request->getPost('token');
            }
            if (empty($accessToken)) {
                $this->forward403($dispatcher);
            } else {
                $redis = mRedis::get_instance();
                $token = $redis->get('auth-accesstoken');
                if ($token === $accessToken) {
                    // good to go
                } else {
                    $this->forward403($dispatcher);
                }
            }
        }
    }

    /**
     * 跳转403
     * @param type $dispatcher
     */
    private function forward403($dispatcher) {
        $dispatcher->forward(array(
            "controller" => "errors", "action" => "show403"
        ));
    }

    /**
     * 获取密钥
     * @param type $RingPs
     */
    private function getKeys($RingPs, $withSecret = false) {
        // appkeyRing
        $Keys = Util::getAesSecretSerial();
        $KeyRingArr = array(
            'abd', 'pos', 'zqm'
        );
        foreach ($KeyRingArr as $index => $rings) {
            if (strpos($rings, $RingPs) > -1) {
                $offset = 0;
                foreach ($Keys as $appSecret => $appKey) {
                    if ($offset == $index) {
                        if ($withSecret) {
                            return array(
                                $appKey, $appSecret
                            );
                        }
                        return $appKey;
                    }
                    $offset++;
                }
            }
        }
    }

}
